<template>
  <NCollapse
    class="nv-collapse"
    :accordion="group.accordion"
    :default-expanded-names
    display-directive="show"
  >
    <NCollapseItem
      v-for="(item, index) in group.items"
      :key="index"
      :name="index"
      :disabled="item.disabled"
    >
      <template #header>
        <component :is="item.icon" v-if="item.icon" />
        <component :is="group.icon" v-else-if="group.icon" />

        <div
          class="nv-collapse-title"
          :style="{
            '--nv-title-font-size': group.size === 'small' ? '14px' : '16px',
          }"
        >
          <component :is="item.title" v-if="typeof item.title === 'function'" />
          <template v-else>
            {{ item.title }}
          </template>
        </div>
        <span
          class="nv-collapse-description"
          :style="{ '--nv-description-text-color': themeVars.textColor2 }"
        >
          {{ item.description }}
        </span>
      </template>

      <NaiveFormFields
        v-model:form="formData"
        :fields="formGroupFields[index]"
        :option="props.option"
        :mode="props.mode"
      >
        <template v-for="(_, name) in slots" #[name]="slotData">
          <slot :name="name" v-bind="slotData || {}" />
        </template>
      </NaiveFormFields>
    </NCollapseItem>
  </NCollapse>
</template>

<script setup lang="ts">
import type { NvFormMode, NvFormOption } from '@/form/types'
import type { RowData } from '@/types'
import { NCollapse, NCollapseItem, useThemeVars } from 'naive-ui'
import { computed } from 'vue'
import NaiveFormFields from '../FormFields.vue'
import { useGroup } from './use-group'

interface Props {
  option: NvFormOption
  mode?: NvFormMode
}
const props = defineProps<Props>()
const slots = defineSlots()

const formData = defineModel<RowData>('form', { required: true })

const themeVars = useThemeVars()
const group = computed(() => props.option.group!)

const defaultExpandedNames = props.option.group?.items
  .map((item, index) => (item.expanded ? index : null))
  .filter(index => index !== null)

const formGroupFields = useGroup(props)
</script>

<style lang="scss">
.nv-collapse {
  flex: 1;

  .nv-collapse-title {
    font-size: var(--nv-title-font-size);
    font-weight: bold;
    margin-left: 5px;
  }
  .nv-collapse-description {
    color: var(--nv-description-text-color);
    margin-left: 8px;
    font-size: 12px;
  }
}
</style>
